
$(function() {
	// 搜索条件太多时折叠
	$("body").on("click", "a.accordion-collapse, .toolbar-collapse, .toolbar-more", function(e, collapse) {
		if (collapse === true || $(e.target).is("a.accordion-collapse, .toolbar-collapse, .toolbar-more")) {
			e.preventDefault();
			var pnl = $(this).closest(".toolbar-box");
			if (collapse === true || pnl.is(".toolbar-box-expand")) {
				pnl.removeClass("toolbar-box-expand")
					.find("a.accordion-collapse").addClass("accordion-expand");
			} else {
				pnl.addClass("toolbar-box-expand")
					.find("a.accordion-collapse").removeClass("accordion-expand");
			}
			// 调整高度
			if (pnl.parent().is(".layout-body")) {
				// 放在layout下的情况
				var height = pnl.outerHeight() + 1;
				var layout = pnl.closest(".layout");
				var region = pnl.parent().panel("options").region;
				layout.layout("panel", region).panel("resize", {height:height});
				layout.layout("resize");
			} else {
				// 放在datagrid工具栏的情况
				pnl.closest(".x-space").panel("doLayout");
			}
		}
	});

	$("body").on("click", ".x-image-box img", function() {
		window.open(this.src);
	});
});


+function() {
	// 右侧滑出详情
	// 绑定全局关闭事件: $(document.body).zsidebar("bind");
	// 滑出: $(".sidebar-details").zsidebar("show", [fn]);
	// 关闭: $(".sidebar-details").zsidebar("hide", [fn]);
	$.fn.zsidebar = function(operate, options) {
		if ($.isFunction(options)) { options = {callback:options}; }
		var o = $.extend(true, {}, $.fn.zsidebar.defaults, options);
		if (operate == "bind") {
			var hideSelector = o.hideSelector.join(",");
			var bind = function() {
				var clickEvent = o.clickEvent + ".zsidebar";
				$(this).off(clickEvent).on(clickEvent, function(e) {
					doClick.call(this, e, o);
				});
				if (o.callback) {
					o.callback.call(this);
				}
			};
			this.find(hideSelector).each(bind);
			return this.each(function() {
				if (o.bindSelf) {
					bind.call(this);
				} else {
					if ($(this).is(hideSelector)) {
						bind.call(this);
					}
				}
			});
		} else if (operate == "show") {
			return this.each(function() {
				var self = this;
				// 通过JS增加的元素, 要setTimeout才能出来动画效果
				setTimeout(function() { doShow(self, o); }, 0);
			});
		} else if (operate == "hide") {
			return this.each(function() {
				var self = this;
				doHide(self, o);
			});
		}
	};
	var doClick = function(e, o) {
		var handler = this;
		var $target = $(e.target);
		var keepSelector = o.keepSelector.join(",");
		var close = true;
		if (e.target == handler) { // target.is(hideSelector)
			close = true;
		} else if ($target.is(keepSelector)) {
			close = false;
		} else {
			// BUG: 经常会出现元素父节点不全(不一定是被删除的元素)
			// 明明有父节点, $target.parents()却找不到, 原因不明
			// 暂时以父节点中是否出现body来判断, 未包含body时不关闭
			var inBody = false;
			var inKeep = false;
			$target.parents().each(function() {
				if (this == document.body) { inBody = true; }
				if (inKeep) { return true; } // 已经inKeep, 后面就只判断inBody, 其他逻辑跳过
				if (this == handler) {
					inBody = true;  inKeep = false; return false;
				} else if ($(this).is(keepSelector)) {
					inKeep = true;
				}
			});
			close = inBody && !inKeep;
		}
		if (close) {
			doHide(handler, o);
		}
	};
	var doHide = function(node, o) {
		var $node = findNode(node, o);
		var action = true; // 是否需要执行动作
		if (o.hideClass && o.showClass) {
			action = !$node.hasClass(o.hideClass) && $node.hasClass(o.showClass);
		} else if (o.hideClass) {
			action = !$node.hasClass(o.hideClass);
		} else if (o.showClass) {
			action = $node.hasClass(o.showClass);
		}
		$node.trigger("hide.zsidebar", action);
		if (action) {
			o.showClass && $node.removeClass(o.showClass);
			o.hideClass && $node.addClass(o.hideClass);
			setTimeout(function() { // 动画效果结束后执行回调函数/触发事件
				if (o.callback) { o.callback.call($node.get(0), isHidden); }
				$node.trigger("hidden.zsidebar", action); // action=有没有执行动作
			}, o.animationDuration);
		} else {
			if (o.callback) { o.callback.call($node.get(0), isHidden); }
			$node.trigger("hidden.zsidebar", action); // action=有没有执行动作
		}
	};
	var doShow = function(node, o) {
		var $node = findNode(node, o);
		var action = false; // 是否需要执行动作
		if (o.hideClass && o.showClass) {
			action = $node.hasClass(o.hideClass) && !$node.hasClass(o.showClass);
		} else if (o.hideClass) {
			action = $node.hasClass(o.hideClass);
		} else if (o.showClass) {
			action = !$node.hasClass(o.showClass);
		}
		$node.trigger("show.zsidebar", action);
		if (action) {
			o.hideClass && $node.removeClass(o.hideClass);
			o.showClass && $node.addClass(o.showClass);
			setTimeout(function() { // 动画效果结束后执行回调函数
				if (o.callback) { o.callback.call($node.get(0), isShown); }
				$node.trigger("shown.zsidebar", action); // action=有没有执行动作
			}, o.animationDuration);
		} else { // 之前已经是显示状态, 不需要执行动作, 直接执行回调函数/触发事件
			if (o.callback) { o.callback.call($node.get(0), isShown); }
			$node.trigger("shown.zsidebar", action); // action=有没有执行动作
		}
	};
	var findNode = function(node, o) {
		var $node = $(node);
		if ($node.is(o.nodeSelector)) {
			return $node;
		}
		var options = $node.zoptions();
		if (!options.boxSelector) {
			var box = $node.closest(o.nodeSelector);
			if (box.length > 0) {
				return box;
			}
		}
		var box = $node.closest(options.boxSelector || o.boxSelector);
		if (box.length == 0) { box = $node; }
		return box.find(o.nodeSelector);
	};
	$.fn.zsidebar.defaults = {
		animationDuration: 500,
		bindSelf: true,
		clickEvent: "click",
		showClass: "in",
		hideClass: "",
		boxSelector: "body",
		nodeSelector: ".sidebar-details",
		hideSelector: [".sidebar-details-hide"],
		keepSelector: [".sidebar-details", ".sidebar-details-keep"]
	};
}(jQuery);


$(function() {
	// 选择子系统
	$("ul.logo-actions li.selected-box").click(function(e) {
		e.preventDefault();
		var ul = $(this).closest(".logo-actions");
		if (ul.hasClass("open")) {
			ul.removeClass("open");
		} else {
			ul.addClass("open");
			var box = ul.find("li.dropdown-box");
			if (!box.data("initialized")) { // 未曾初始化
				// 显示正在加载的提示
				ul.find(".dropdown-box .loading").removeClass("hide");
				// 查询拥有权限的子系统
				var currCode = $(this).find(".logo-box").attr("data-factory");
				$.post(ul.data("mine-url"), function(json) {
					ul.find(".dropdown-box .loading").addClass("hide");
					box.data("initialized", true); // 标记已经初始化
					var exist = false;
					if (json.body && json.body.length) {
						box.find(".logo-box").remove();
						var tpl = ul.find("li.template-box").html();
						$.each(json.body, function() {
							if (this.tenantCode == currCode) { return true; }
							exist = true;
							$(tpl).appendTo(box).attr("data-factory", this.tenantCode)
								.find(".text").text(this.name);
						});
					}
					if (!exist) { ul.find(".dropdown-box .nomore").removeClass("hide"); }
				});
			}
		}
	});
	$("ul.logo-actions li.dropdown-box").on("click", ".logo-box", function() {
		var ul = $(this).closest(".logo-actions");
		var factory = $(this).attr("data-factory");
		$.post(ul.data("change-url"), {tenantCode:factory}, function(json) {
			ul.removeClass("open");
			$("ul.logo-actions li.selected-box").find(".logo-box")
				.attr("data-factory", json.body.tenantCode)
				.find(".text").text(json.body.name);
			window.location.href = $("meta[name=relative-path]").attr("content");
		});
	});
});

$(function() {
	// 退出登录
	$("a.action-logout, button.action-logout").click(function(e) {
		var href = $(this).data("href");
		var options = $(this).zoptions();
		if (options.confirm === false) {
			window.location.href = href;
		} else {
			$.messager.confirm("注销", "确认退出系统？", function (ok) {
				if (ok) {
					window.location.href = href;
					return true;
				}
			});
		}
		e.preventDefault();
	});
	// 查看个人详情
	$(".open-mine-details").click(function(e) {
		$(".x-dialog.mine-details").xcall("open");
	    e.preventDefault();
	});
	// 修改自己的密码
	$(".modify-mine-password").click(function(e) {
		$(".x-dialog.modify-mine-password").xcall("open");
	    e.preventDefault();
	});
});


$(function() {
	// 登录对话框初始化
	$(".x-dialog.login").xui({
		onOpen:function() {
			$(this).find("a.captcha").trigger("click");
		},
		doLogout:function() {
			window.location.href = $("input[name=home-page]").val();
		},
		onLoginSuccess:function(e) {
			var key = "login-refresh-panel";
			var opts = e.popup.xcall("options");
			var pnl = opts[key];
			if (pnl) {
				opts[key] = undefined;
				pnl.panel("refresh");
			}
		}
	});
	// 切换验证码
	$(".x-dialog.login").find("a.captcha").click(function(e) {
		e.preventDefault();
		var me = $(this);
		me.children("img").attr("src", me.attr("data-url") + "?" + new Date().getTime());
	});
	// 个人详情对话框初始化
	$(".x-dialog.mine-details").xui({
		doModifyPassword:function() {
			var opts = $(this).xcall("options");
			opts.xref.popup.xcall("close");
			$(".x-dialog.modify-mine-password").xcall("open");
		}
	});
	// 修改密码对话框初始化
	$(".x-dialog.modify-mine-password").xui({
		onBeforeSubmit:function(e) {
			if (e.form.find("input[name=oldPassword]").val() == e.form.find("input[name=newPassword]").val()) {
				$(this).warnning("新密码和原密码不能相同!");
				return false;
			}
			if (e.form.find("input[name=newPassword]").val() != e.form.find("input[name=confirmPassword]").val()) {
				$(this).warnning("新密码和确认密码必须相同!");
				return false;
			}
		}
	});

});


/**
 * 左侧菜单的点击处理, 打开新的TAB页
 */
$(function() {

	$(".main-tabs").xui("init");

	var content = $(document.body).find(".lyt-contents");
	var sidebar = $(document.body).find(".lyt-sidebar .sidebar-menu");

	// 左侧菜单的点击事件
	sidebar.on("click", "a[href]", function(e) {
		var me = $(this);

		var hash = me.attr("href");
		if (!hash || !hash.startsWith('#')) { return; }
		var options = me.zoptions();
		// open=true表示打开新窗口
		if (options.open == false) { return; }
		me.closest(".sidebar-menu").find("li.active").removeClass("active");
		me.parent().addClass("active").parents("li.header").addClass("active");
		var title = options.title || me.text();
		var o = $.extend({ hash:hash, title:title, menu:me }, options);
		hash && $(".main-tabs").tabs("xopen", o);
		if (o.homepage) { e.preventDefault(); }
	})
	.on("open.sidebar", function(e, hash) {
		$(this).find("a").each(function() {
			var href = $(this).attr("href");
			if (!href || href == "#") { return true; } // 菜单组
			if (!hash || href == hash) {
				$(this).click();
				return false;
			}
		});
	})
	.on("selected.sidebar", function(e, item) {
		if ($.dt.isString(item)) {
			var hash = item && item.replace(/^[\.#]+(\/[\.#]+)*/, "");
			$(this).find("a").each(function() {
				var href = $(this).attr("href");
				if (!href || href == "#") { return true; } // 菜单组
				href = href && href.replace(/^[\.#]+(\/[\.#]+)*/, "");
				if (href == hash) {
					var item = $(this);
					item.closest(".sidebar-menu").find("li.active").removeClass("active");
					item.parent().addClass("active").parents("li.header").addClass("active");
					return false;
				}
			});
		} else {
			item.closest(".sidebar-menu").find("li.active").removeClass("active");
			item.parent().addClass("active").parents("li.header").addClass("active");
		}
	})
	.on("click", "li.header > a", function(e) { // 打开/关闭子菜单
		var me = $(this);
		var hash = me.attr("href");
		if (hash && hash != "#") { return; }

		e.preventDefault();

		var li = me.parent();
		if (li.is(".active")) {
			li.removeClass("active");
		} else {
			li.siblings("li.header.active").removeClass("active")
				.parents("li.header.active").removeClass("active");
			li.addClass("active").parents("li.header").addClass("active");
		}
	});

	// 根据location.hash初始化左侧菜单
	sidebar.trigger("open", window.location.hash);

});



(function($) {
$.extend($.fn.validatebox.defaults.rules, {
	ascii : {
		validator : function(value) {
			return /^[\x00-\x7F]*$/.test(value);
		},
		message : "请输入英文字符"
	},
	code : { // 编号
		validator : function(value) {
			return /^[a-z0-9]*$/i.test(value);
		},
		message : "请输入数字或字母"
	},
	digits : { // 数字
		validator : function(value) {
			return /^[0-9]*$/.test(value);
		},
		message : "请输入数字"
	},
	idcard : { // 验证身份证
		validator : function(value) {
			return /^(\d{15}(\d{2}[xX0-9])?)?$/.test(value);
		},
		message : "身份证号码格式不正确"
	},
	telphone : { // 固定电话或400或800电话
		validator : function(value) {
			return /^(([48]00-?\d{3}-?\d-?\d{3}|0\d{2,3}\-\d{5,8})(\-\d{1,4})?)?$/.test(value);
		},
		message : "电话号码格式不正确"
	},
	mobile : { // 验证手机号码
		validator : function(value) {
			return /^(1\d{10})?$/.test(value);
		},
		message : "手机号码格式不正确"
	},
	phone : { // 固定电话或手机号码
		validator : function(value) {
			return /^(1\d{10}|([48]00-?\d{3}-?\d-?\d{3}|0\d{2,3}\-\d{5,8})(\-\d{1,4})?)?$/.test(value);
		},
		message : "请输入固定电话或手机号码"
	},
	illegalChar : { // 特殊字符
		validator : function(value) {
			return !/[<>"\\]/.test(value);
		},
		message : "不支持<>\"\\等特殊字符"
	},
	// extension:['图片','jpg|jpeg|png|bmp']
	extension : {
		validator : function(value, params){
			var regexp = new RegExp("\.(" + params[1] + ")$");
			return regexp.test(value);
		},
		message : "请上传{0}格式的文件"
	}
});
})(jQuery);


(function($) {
	/**
	var genders = { UNKNOWN:"未知", MALE:"男", FEMALE:"女" };
	var genderToText = function(value) {
		// 单纯的将枚举转换为文本
		// return Utils.formatEnumValue(genders, value);
		// 某种枚举值以红色显示
		return Utils.formatEnumValue(genders, value, this, value == "UNKNOWN");
	};
	**/
	var formatEnumValue = function(enums, value, node, warnning) {
		if (!value) { return value; }
		var text = enums[value];
		if (warnning === undefined) {
			return text;
		}
		if (node.tagName && node.tagName.toUpperCase() == "INPUT") {
			var input = $(node);
			if (input.is(".x-textbox")) {
				input = input.textbox("textbox");
			}
			if (warnning) {
				input.addClass("warn");
			} else {
				input.removeClass("warn");
			}
			return text;
		} else {
			return warnning ? wrapWarnning(text) : text;
		}
	};
	var wrapWarnning = function(value) {
		return '<span class="warn">' + value + '</span>';
	};
	// 根据状态显示右键菜单项
	var doShowMenuItem = function(menu, state) {
		menu.children().each(function() {
			var me = $(this);
			if (me.is(".ALL") || me.is(".menu-sep")) {
				return true;
			}
			if (state && me.hasClass(state)) {
				menu.menu("showItem", this);
			} else {
				menu.menu("hideItem", this);
			}
		});
	};
	// 解决重复加载页面时, 对话框/右键菜单/选择框下拉层冲突的问题
	var initialize = function(type) {
		var separator = "initialize-separator";
		var selector = $.zhh.format(".{0}.{1}", separator, type);
		var old = $(selector);
		if (old.length > 0) {
			old.nextAll().each(function() {
				var me = $(this);
				if (me.hasClass(separator)) {
					return false;
				} else {
					me.remove();
				}
			});
			old.remove();
		}
		var html = $.zhh.format('<div class="{0} {1}">', separator, type);
		$(document.body).append(html);
	};
	// 枚举转换为map
	var enumsToMap = function(enums) {
		var map = {};
		$.each(enums, function() {
			map[this.key] = this.value;
		});
		return map;
	};
	// Utils.map("aaa bbb ccc ddd")
	// Utils.map("aaa bbb", "ccc ddd")
	// --> "({aaa:aaa,bbb:bbb,ccc:ccc})"
	var map = function(keys) {
		var list = [];
			$.each(arguments, function(i, keys) {
			if (typeof(keys) == "string") {
				keys = $.trim(keys).split(/[ ,]+/g);
			}
			$.each(keys, function(i, key) {
				if (key && (typeof(key) == "string")) {
					list.push(key + ":" + key);
				}
			});
		});
		return "({" + list.join(",") + "})";
	};
	var dateClearTime = function(value) {
		return value && value.substring(0, 10);
	};
	// 克隆
	var clone = function(object) {
		if ($.isArray(object)) {
			var array = [];
			$.each(object, function() {
				array.push(clone(this));
			});
			return array;
		} else {
			return $.extend(true, {}, object);
		}
	};
	var ueditorId = 0;
	var ueditor = {
		create: function(space, selector, params) {
			var editor = space.find(selector).eq(0);
			var id = "ueditor-" + (ueditorId++);
			editor.attr("id", id);
			return UE.getEditor(id, params);
		}
	};

	if (!window.Utils) { window.Utils = {}; }
	$.extend(window.Utils, {
		clone:clone, map:map,
		doShowMenuItem:doShowMenuItem,
		wrapWarnning:wrapWarnning, formatEnumValue:formatEnumValue,
		enumsToMap:enumsToMap,
		ueditor:ueditor, dateClearTime:dateClearTime
	});
	$.fn.xui.defaults.globalVariables.push("Utils");
})(jQuery);


